﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using MySql.Data.MySqlClient;
using Gollie.Mail;

namespace Gollie.Ajax
{
	public class RegisterConsumer : AjaxResult
	{
		public RegisterConsumer() : base(null) { }

		public RegisterConsumer(AjaxArg arg)
			: base(arg)
		{

		}

		protected override void Init(AjaxArg ajaxArg)
		{
			RegisterConsumerArg arg = (RegisterConsumerArg)ajaxArg;

			logger.Info("Consumer registration attempt...");

			try
			{
				string initials = UserInfo.ValidateInitials(arg.initials.Trim());
				string infix = arg.infix.Trim();
				string sex = arg.sex;
				string lastname = arg.lastname.Trim();
				string city = arg.city.Trim();
				string username = arg.tokenUser.Trim().ToLower();
				string ww = arg.ww;
				string email = arg.email.Trim();
				string mobile = arg.mobile.Trim().Replace("-", "").Replace(" ", "");
				string pin = arg.pin;
				string birthdate = arg.birthdate.Trim();

				UserInfo.ValidateUserName(username);
				UserInfo.ValidateWW(ww);
				UserInfo.ValidateEmail(email);
				mobile = UserInfo.ValidateTelePhone(mobile, true);
				UserInfo.ValidatePin(pin);
				DateTime bdate = UserInfo.ValidateBirthdate(birthdate);

				/* Validation success! */
				string hashed = Database.Queries.RegisterUser(username, 4, Hash.GetHash(ww), email, initials, infix, lastname, (sex == "1"), city, bdate, mobile, 1, Hash.GetHash(pin));

				logger.Info("Consumer registered {0}", username);

				UserInfo userInfo = new UserInfo(initials, infix, lastname, (sex == "1"), email);

				MailClient.Queue(new EMail
				{
					Name = "activateaccount",
					Recipients = email,
					Args = new Dictionary<string, string>()
					{
												{ "{activationurl}", ConfigAppSettings.GetValue("UserActivationUrl") },
												{ "{aanhef}", userInfo.MailAanhef },
												{ "{hasheduid}", hashed }
										    
					}
				});
			}
			catch (MySqlException mySqlEx)
			{
				this.ErrorCode = mySqlEx.Number;
				this.ErrorMessage = MySqlErrorCodes.GetInstance().GetMessage(mySqlEx);
				logger.Error("Consumer registration failed: {0}", this.ErrorMessage);
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
				logger.Error("Consumer registration failed: {0}", this.ErrorMessage);
			}
		}
	}
}